package com.d3.sx_eprotection.service.serviceImp;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.d3.sx_eprotection.entity.Administrator;
import com.d3.sx_eprotection.intercepter.JWTUtil;
import com.d3.sx_eprotection.mapper.AdministratorMapper;
import com.d3.sx_eprotection.service.AdministratorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdministratorServiceImp extends ServiceImpl<AdministratorMapper, Administrator> implements AdministratorService {
    @Resource
    private AdministratorMapper administratorMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final Logger log = LoggerFactory.getLogger(SupervisorServiceImp.class);
    @Override
    public Administrator find(Administrator administrator) {
        return administratorMapper.find(administrator.getAdmin_code());
    }

    @Override
    public Map<String, Object> login(Administrator administrator) {
        Map<String,Object> result = new HashMap<>();
        try{
            Map<String,Object> testmap = new HashMap<>();
            testmap.put("admin_code",administrator.getAdmin_code());
            testmap.put("password",administrator.getPassword());
            Administrator get = administratorMapper.selectByMap(testmap).get(0);
            if (get!=null){
                Map<String, String> payload = new HashMap<>();
                //封装payload,这里面放需要前台未来用来验证的信息
                payload.put("admin_code", String.valueOf(administrator.getAdmin_code()));
                payload.put("name", administrator.getName());
                payload.put("password", administrator.getPassword());
                // 生成token
                String token = JWTUtil.getToken(payload);
                result.put("status", true);
                result.put("msg", "登录成功");
                result.put("token", token); // 响应token，存储在客户端
                //存储todo....redis
                redisTemplate.opsForValue().set(administrator.getAdmin_code(), token, 30, TimeUnit.MINUTES);
            }else {
                log.info("编码或密码有误");
                result.put("status", false);
                result.put("msg", "登录失败");
            }
        } catch (Exception e){
            log.info("登录失败...");
            result.put("status", false);
            result.put("msg", "登录失败");
        }
        return result;
    }

}
